﻿using Microsoft.AspNetCore.Mvc;
using Projects.Models;
using Projects.Data;
using Microsoft.EntityFrameworkCore;
using static Projects.Controllers.WayController;

namespace Projects.Controllers
{
    public class WayController : Controller
    {
        private  Projects.Data.ProjectsContext _context;
        public struct Result 
        {
            public string response {  get; set; }
            public Project project { get; set; }

        }
        public WayController(Projects.Data.ProjectsContext context) { _context = context; }

        [HttpGet("FindByProductId/{project_id}")]
        public ActionResult<Result> findbyproduct_id(int project_id)
        {
            // 尝试从数据库中查找具有指定 product_id 的项目
            Project foundProject = _context.Project.FirstOrDefault(p => p.project_id == project_id);
            Result result = new Result();
            if (foundProject != null)
            {
                result.response = "找到项目";
                result.project = foundProject;
            }
            else
            {
                result.response = "未找到项目";
                result.project = null;
            }
            return result;
        }
        public struct Message
        {
            public string response { get; set; }
            

        }
        [HttpPut("PutByProjectId/{project_id}")]
        public async Task<ActionResult<Message>> putbyproject_id(int project_id, [FromBody] Project updateproject)
        {
            Message message = new Message();
            try
            {
                // 查询项目是否存在
                Project foundProject = _context.Project.FirstOrDefault(p => p.project_id == project_id);
                if (foundProject == null)
                {
                    return NotFound(new Message { response = "项目不存在" });
                }

                if (project_id != updateproject.project_id)
                {
                    return BadRequest(new Message { response = "传入的项目ID与请求路径中的ID不一致" });
                }

                // 检查并移除已跟踪的相同键值的实体（如果存在）
                var trackedEntity = _context.ChangeTracker.Entries<Project>()
                                                   .FirstOrDefault(e => e.Entity.project_id == project_id);
                if (trackedEntity != null)
                {
                    _context.Entry(trackedEntity.Entity).State = EntityState.Detached;
                }

                _context.Entry(updateproject).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                message.response = "修改成功";
                return message;
            }
            catch (Exception ex)
            {
                // 记录异常等错误处理逻辑，可根据实际完善
                Console.WriteLine($"更新项目出现异常: {ex.Message}");
                message.response = "更新项目出现异常，请联系管理员";
                return StatusCode(500, message);
            }
        }

        [HttpPut("PutByCtaegoryId/{category_id}")]
        public async Task<ActionResult<Result>> putbycategory_id(int category_id, [FromBody] Category updatecategory)
        {
            Result result = new Result();
            try
            {
                // 查询类目是否存在
                Category foundCategory = _context.Category.FirstOrDefault(p => p.category_id == category_id);
                if (foundCategory == null)
                {
                    return BadRequest("类目不存在");
                }

                if (category_id != updatecategory.category_id)
                {
                    return BadRequest("传入的类目ID与请求路径中的ID不一致");
                }

                // 检查并移除已跟踪的相同键值的实体（若存在）
                var trackedEntity = _context.ChangeTracker.Entries<Category>()
                                                  .FirstOrDefault(e => e.Entity.category_id == category_id);
                if (trackedEntity != null)
                {
                    _context.Entry(trackedEntity.Entity).State = EntityState.Detached;
                }

                _context.Entry(updatecategory).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return NoContent();
            }
            catch (Exception ex)
            {
                // 记录异常等错误处理逻辑，可按需完善
                Console.WriteLine($"更新类目出现异常: {ex.Message}");
                result.response = "更新类目出现异常，请联系管理员";
                return StatusCode(500, result);
            }
        }
        



    }
}
